﻿using Kingdee.BOS.Core.CommonFilter;
using Kingdee.BOS.Core.DynamicForm;
using Kingdee.BOS.Core.DynamicForm.PlugIn;
using Kingdee.BOS.Core.DynamicForm.PlugIn.Args;
using Kingdee.BOS.Core.List;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.Util;
using System;
using System.Collections.Generic;
using Kingdee.BOS.Core.Metadata.ControlElement;
using Kingdee.BOS.Core.DynamicForm.PlugIn.ControlModel;
using Kingdee.BOS.JSON;
using Kingdee.BOS.Core.Metadata.FieldElement;
using Kingdee.BOS.App.Data;
using System.Linq;
using Kingdee.BOS.Core.Metadata.ConvertElement;
using Kingdee.BOS.Orm;
using Kingdee.BOS.Core.Metadata.ConvertElement.ServiceArgs;
using Kingdee.BOS.Core.DynamicForm.Operation;
using Kingdee.BOS.Core.Bill;
using Kingdee.BOS.Core.Metadata;
using Kingdee.BOS.ServiceHelper;
using Kingdee.BOS.Business.Bill.Utils;
using System.Text;

namespace K.KDL
{
    public class ArMatchStencilEdit : AbstractDynamicFormPlugIn
    {
        const string OS_LINES_SQL = @"/*dialect*/SELECT OS.FID, OS.FBILLNO, OS.FDATE, OS.FCUSTOMERID
	                                    , OSE.FENTRYID, OSE.FSEQ, OSE.FMATERIALID
                                        , OSEF.FPRICEUNITID, OSEF.FPRICEUNITQTY, OSER.FARNOTJOINQTY
                                        , OSEF.FPRICE, OSEF.FTAXRATE, OSEF.FTAXPRICE
                                        , OSEF.FAMOUNT, OSEF.FTAXAMOUNT, OSEF.FALLAMOUNT
                                    FROM T_SAL_OUTSTOCK OS
                                    INNER JOIN T_SAL_OUTSTOCKENTRY OSE ON OS.FID=OSE.FID
                                    INNER JOIN T_SAL_OUTSTOCKENTRY_F OSEF ON OSE.FENTRYID=OSEF.FENTRYID
                                    INNER JOIN T_SAL_OUTSTOCKENTRY_R OSER ON OSEF.FENTRYID=OSER.FENTRYID
                                    WHERE OSE.FENTRYID IN ({0});";

        const string RS_LINES_SQL = @"/*dialect*/SELECT RS.FID, RS.FBILLNO, RS.FDATE, RS.FRETCUSTID AS FCUSTOMERID
	                                    , RSE.FENTRYID, RSE.FSEQ, RSE.FMATERIALID
                                        , RSEF.FPRICEUNITID, RSEF.FPRICEUNITQTY, RSER.FARNOTJOINQTY
                                        , RSEF.FPRICE, RSEF.FTAXRATE, RSEF.FTAXPRICE
                                        , RSEF.FAMOUNT, RSEF.FTAXAMOUNT, RSEF.FALLAMOUNT
										FROM T_SAL_RETURNSTOCK RS
                                    INNER JOIN T_SAL_RETURNSTOCKENTRY RSE ON RS.FID=RSE.FID
                                    INNER JOIN T_SAL_RETURNSTOCKENTRY_F RSEF ON RSE.FENTRYID=RSEF.FENTRYID
                                    INNER JOIN T_SAL_RETURNSTOCKENTRY_R RSER ON RSEF.FENTRYID=RSER.FENTRYID
                                    WHERE RSE.FENTRYID IN ({0});";

        public override void OnInitialize(InitializeEventArgs e)
        {
            base.OnInitialize(e);
        }

        public override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            var orgId = Convert.ToInt64(this.View.OpenParameter.GetCustomParameter("OrgId").ToString());
            if (orgId > 0)
            {
                this.View.BusinessInfo.FillBaseDataField(Context, this.View.Model.DataObject, "FOrgId", orgId);
                this.View.UpdateView("FOrgId");
            }

            var custId = Convert.ToInt64(this.View.OpenParameter.GetCustomParameter("CustId").ToString());
            if (custId > 0)
            {
                this.View.BusinessInfo.FillBaseDataField(Context, this.View.Model.DataObject, "FCustomer", custId);
                this.View.UpdateView("FCustomer");
            }
        }

        public override void BarItemClick(BarItemClickEventArgs e)
        {
            base.BarItemClick(e);

            if (e.BarItemKey != null)
            {
                switch (e.BarItemKey)
                {
                    case "tbUpFilter":
                        ShowFilter(true);
                        break;
                    case "tbDownFilter":
                        ShowFilter(false);
                        break;
                    case "tbRefresh":
                        break;
                    case "tbReturnData":
                        ReturnData();
                        break;
                    default:
                        break;
                }
            }
        }

        private void ShowFilter(bool isUP)
        {
            // TODO: 添加组织机构及客户过滤条件
            var directionSuffix = isUP ? "UP" : "DOWN";
            var showParameter = new ListSelBillShowParameter();
            showParameter.FormId = isUP ? "SAL_OUTSTOCK" : "SAL_RETURNSTOCK";
            showParameter.OpenStyle.ShowType = ShowType.Floating;
            //showParameter.PageId = Guid.NewGuid().ToString();
            showParameter.ParentPageId = this.View.PageId;
            showParameter.IsLookUp = true;
            showParameter.MultiSelect = true;
            showParameter.IsShowUsed = true;
            showParameter.PageId = Guid.NewGuid().ToString();
            showParameter.IsShowApproved = true;
            showParameter.IsIsolationOrg = true;
            showParameter.TargetMainOrgId = (long)this.View.Model.DataObject["FOrgId_Id"];
            showParameter.UseOrgId = (long)this.View.Model.DataObject["FOrgId_Id"];
            showParameter.ListType = 3;
            var filter = new StringBuilder();
            filter.Append(" FDOCUMENTSTATUS='C'");
            filter.Append(" AND ABS(FPRICEBASEQTY) > ABS(FBaseARJoinQty)");
            if (Convert.ToInt64(this.View.Model.DataObject["FCustomer_Id"]) > 0)
            {
                var custNumber = (this.View.Model.DataObject["FCustomer"] as DynamicObject)["Number"];
                filter.Append(isUP
                    ? $" AND FCUSTOMERID.FNumber='{custNumber}'"
                    : $" AND FRETCUSTID.FNumber='{custNumber}'");
            }
            showParameter.ListFilterParameter.Filter = showParameter.ListFilterParameter.Filter.JoinFilterString(filter.ToString());

            string hiddenMnus = "tbSNew,tbDelete,tbSplitSubmit,tbSplitApprove,tbBusinessPush,tbCancel";
            showParameter.CustomParams.Add("HiddenMnus", hiddenMnus);
            this.View.ShowForm(showParameter, (x) =>
            {
                var result = x.ReturnData as ListSelectedRowCollection;
                if (result == null || result.Count == 0) return;

                this.View.Model.ClearNoDataRow();
                var entryKey = $"F{directionSuffix}Entity";
                var entryEntity = this.View.BillBusinessInfo.GetEntryEntity(entryKey);
                var entry = this.View.Model.GetEntityDataObject(entryEntity);

                // TODO: 排除重复行
                var entryIDs = string.Join(",", result
                    .Where(_ => !entry.Any(__ => __[$"F_{directionSuffix}_ENTRYID"]?.ToString() == _.EntryPrimaryKeyValue))
                    .Select(_ => _.EntryPrimaryKeyValue));
                if (string.IsNullOrWhiteSpace(entryIDs)) return;
                var selectedLines = DBUtils.ExecuteDynamicObject(Context, string.Format(isUP ? OS_LINES_SQL : RS_LINES_SQL, entryIDs));

                var index = entry.Count;
                foreach (var line in selectedLines)
                {
                    this.View.Model.CreateNewEntryRow(entryKey);
                    var newLine = this.View.Model.GetEntityDataObject(entryEntity, index);

                    this.View.Model.SetValue($"F_{directionSuffix}_ID", line["FID"], index);
                    this.View.Model.SetValue($"F_{directionSuffix}_ENTRYID", line["FENTRYID"], index);
                    this.View.Model.SetValue($"F_{directionSuffix}_BILLNO", line["FBILLNO"], index);
                    this.View.Model.SetValue($"F_{directionSuffix}_DATE", line["FDATE"], index);
                    this.View.Model.SetValue($"F_{directionSuffix}_CUSTOMER", line["FCUSTOMERID"], index);
                    //this.View.BillBusinessInfo.FillBaseDataField(Context, newLine, $"F_{directionSuffix}_CUSTOMER", line["FCUSTOMERID"]);
                    //this.View.Model.SetValue($"F_{directionSuffix}_CUSTOMER", line["FCUSTOMERID"], index);
                    this.View.Model.SetValue($"F_{directionSuffix}_SEQ", line["FSEQ"], index);
                    this.View.Model.SetValue($"F_{directionSuffix}_MATERIAL", line["FMATERIALID"], index);
                    this.View.Model.SetValue($"F_{directionSuffix}_UNITID", line["FPRICEUNITID"], index);
                    this.View.Model.SetValue($"F_{directionSuffix}_QTY", line["FPRICEUNITQTY"], index);
                    this.View.Model.SetValue($"F_{directionSuffix}_PRICE", line["FPRICE"], index);
                    this.View.Model.SetValue($"F_{directionSuffix}_TAXRATE", line["FTAXRATE"], index);
                    this.View.Model.SetValue($"F_{directionSuffix}_TAXPRICE", line["FTAXPRICE"], index);
                    this.View.Model.SetValue($"F_{directionSuffix}_AMOUNT", line["FAMOUNT"], index);
                    this.View.Model.SetValue($"F_{directionSuffix}_TAXAMOUNT", line["FTAXAMOUNT"], index);
                    this.View.Model.SetValue($"F_{directionSuffix}_ALLAMOUNT", line["FALLAMOUNT"], index);

                    index++;
                }

                this.View.UpdateView();
            });
        }

        //public override void AfterBarItemClick(AfterBarItemClickEventArgs e)
        //{
        //    base.AfterBarItemClick(e);
        //    string barItemKey;
        //    if ((barItemKey = e.BarItemKey) != null && barItemKey == "tbRefresh")
        //    {
        //        this.GetBillData("1", this._debitFilterPara);
        //        this.GetBillData("-1", this._creditFilterPara);
        //    }
        //}

        private void ReturnData()
        {
            var result = new List<ListSelectedRow>();

            var upEntryEntity = this.View.BillBusinessInfo.GetEntryEntity("FUpEntity");
            var upEntry = this.View.Model.GetEntityDataObject(upEntryEntity);
            if (upEntry != null)
            {
                foreach (var line in upEntry)
                {
                    var row = new ListSelectedRow(line["F_UP_ID"].ToString(), line["F_UP_EntryID"].ToString(), Convert.ToInt32(line["F_UP_SEQ"]), "SAL_OUTSTOCK");
                    row.EntryEntityKey = "FEntity";
                    result.Add(row);
                }
            }

            var downEntryEntity = this.View.BillBusinessInfo.GetEntryEntity("FDownEntity");
            var downEntry = this.View.Model.GetEntityDataObject(downEntryEntity);
            if (downEntry != null)
            {
                foreach (var line in downEntry)
                {
                    var row = new ListSelectedRow(line["F_DOWN_ID"].ToString(), line["F_DOWN_EntryID"].ToString(), Convert.ToInt32(line["F_DOWN_SEQ"]), "SAL_RETURNSTOCK");
                    row.EntryEntityKey = "FEntity";
                    result.Add(row);
                }
            }

            this.View.ReturnToParentWindow(result);
            this.View.Close();
        }
    }
}
